package icselab.appmodule.service;
import java.io.File;

import org.jboss.mx.util.MBeanProxyExt;
import org.jboss.mx.util.ObjectNameFactory;
import org.jboss.system.server.ServerConfigImplMBean;

import icselab.appmodule.server.*;
import icselab.dbaccess.DeployDAO;
import icselab.dbaccess.MonitorDAO;
import icselab.util.Transmission;


public class DeployService {
	
    private static final String DOWNLOADING = "downloading";
    private static final String UNDEPLOYED = "undeployed";
    private static final String DONE = "done";
	
	public String deploy(String sUrl){
		
		System.out.println("checking deploy location...");
			
		String deployDir = this.getDeployDir(sUrl);
		System.out.println("deploy the instance at "+ deployDir);
   
		//transfer and decompress the service package 
        File file = new File(deployDir);   
		file.mkdirs();	
        if(deployDir != null){
			new Transmission(sUrl, deployDir).start();
		}     
        
        String[] folders = deployDir.split("/");
        String instanceName = folders[folders.length-1];
        String instanceID = instanceName.substring(0, instanceName.lastIndexOf("."));
        
        //record the instance in database
        DeployDAO dda = new DeployDAO();
        dda.insertDeployInfo(instanceID, deployDir); 
        
        //start a new thread to check deployment status
        new DeploymentChecker(instanceID, "file:"+deployDir).start();
		return "/"+instanceID+"/";
	}
	

	/*
	 * stop a instance by id
	 */
	public String stopInstance(String instanceID) {
		//get the instance URL
		DeployDAO dda = new DeployDAO();
		String iUrl = dda.getUrlByInstanceID(instanceID);
		
		//instance URL is empty
		if(iUrl == "")
			return "the instance "+instanceID+" does not exist";
		
		// stop the instance
		ServerManager smg = new ServerManager();
		if(smg.stopInstance(iUrl))
		{
			dda.updateDeployInfo(instanceID, UNDEPLOYED);
			System.out.println("stop the instance at "+ iUrl);
			return "stop service " + instanceID + " successfully";
		}
		else
			return "fail to stop service " + instanceID;
	}
	
	/*
	 * start instance by id
	 */
	public String startInstance(String instanceID){
		//get the instance Url
		DeployDAO dda = new DeployDAO();
		String iUrl = dda.getUrlByInstanceID(instanceID);
		
		//instance URL is empty
		if(iUrl == "")
			return "the instance "+instanceID+" does not exist";
		
		// start the instance
		ServerManager smg = new ServerManager();
		if(smg.startInstance(iUrl))
		{
			dda.updateDeployInfo(instanceID, DONE);
			System.out.println("start the instance at "+ iUrl);
			return "start service " + instanceID + " successfully";
		}
		else
			return "fail to start service " + instanceID;
	}
	
	/*
	 * remove instance by id
	 */
	public String removeInstance(String instanceID){
		//get the instance Dir and URL
		DeployDAO dda = new DeployDAO();
		MonitorDAO mda = new MonitorDAO();
		String iUrl = dda.getUrlByInstanceID(instanceID);
		String iDir = dda.getDirByInstanceID(instanceID);
		
		//instance URL is empty
		if(iUrl == "")
			return "the instance "+iUrl+" does not exist";
		if(iDir == "")
			return "the instance dir "+iDir+" does not exist";
		
		// stop the instance
		System.out.println("stop the instance at "+ iDir);
		ServerManager smg = new ServerManager();
		if(smg.stopInstance(iUrl)){		
			//should be the directory, not URL
			File file = new File(iDir);
			if(file.exists()){
				System.out.println("Remove the dir: "+iDir);
				this.deleteFiles(file);
				dda.deleteDeployInfo(instanceID);
				mda.deleteMonitorStat(instanceID);
				return "remove instance " + instanceID + " completely.";
			}
			System.out.println("fail to stop instance at "+iUrl);
		}
	
		//fail to remove the instance Dir
		System.out.println("dir does not exist: "+iDir);
		return "fail to remove the instance "+instanceID;
	}
	
	/*
	 * delete file
	 */
	private void deleteFiles(File file){
		if (file.isDirectory()){
			File[] subfiles = file.listFiles();
			for (int i = 0; i < subfiles.length; i++)
				deleteFiles(subfiles[i]);
			file.delete();
		}
		else{
			file.delete();
		}
		
	}
	
	private String getDeployDir(String sUrl){
		
		String deployDir = "";
		String serverDir = "";
		ServerConfigImplMBean configBean = (ServerConfigImplMBean) 
		   MBeanProxyExt.create(ServerConfigImplMBean.class, ObjectNameFactory.create("jboss.system:type=ServerConfig"));
		
		serverDir = configBean.getServerHomeDir().toString().replace('\\', '/') + "/deploy/";
		int zipIndex = sUrl.lastIndexOf(".zip");
		
		if(zipIndex == 0){
			System.err.println("unsupported url target,zip file only");
			return null;
		}	
		else{
			deployDir = serverDir+"ws"+sUrl.substring(sUrl.lastIndexOf("/")+1,zipIndex);
		}
              
    	return deployDir + '/';
	}	

}
